package logic

import (
	"context"
	"examrpc/models/mysql"
	"examrpc/models/redis"
	"examrpc/pkg"
	"fmt"

	"examrpc/examrpc/examrpc"
	"examrpc/examrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *examrpc.UpdatePasswordRequest) (*examrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&findUser)
	if findUser.ID == 0 {
		return nil, fmt.Errorf("当前账号为注册，请前去注册")
	}
	if findUser.Password != pkg.Md5(in.OldPassword) {
		return nil, fmt.Errorf("原密码输入错误，请重新输入")
	}
	if in.NewPassword != in.AckPassword {
		return nil, fmt.Errorf("两次新密码不一致，请重新输入")
	}
	if findUser.Password == pkg.Md5(in.NewPassword) {
		return nil, fmt.Errorf("新密码与原密码一致，禁止修改")
	}
	if in.NewPassword == "" {
		return nil, fmt.Errorf("新密码不能为空")
	}
	sms := redis.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if sms.Val() != in.SmsCode {
		return nil, fmt.Errorf("当前短信验证码错误，请重新输入")
	}
	redis.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)
	return &examrpc.UpdatePasswordResponse{
		Id: int64(findUser.ID),
	}, nil
}
